package com.xxgc.demo.controller.aop;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @Author: Sjy
 * @Date :2023/10/13 - 10 - 13 - 17:04
 * 数据源管理器
 */
@Component
@Aspect
public class DataSourceMangerAOP {

    private static String source = "master";

    /**
     * 每个请求进来先设置数据源
     */
    @Before("execution(* com.xxgc.demo.controller.*.*(..))")
    public void dataSourceManger(){
        //每一个请求进来都设置数据源
        DynamicDataSourceContextHolder.push(source);
    }

    /**
     * 动态切换数据源
     * @param name
     */
    public static void changeSource(String name){
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push(name);
        source = name;
    }

    /**
     * 获取当前数据源
     */
    public static String getSource(){
        return source;
    }

}